package com.resou.reader;


import android.app.AlertDialog;
import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fm.openinstall.OpenInstall;
import com.resou.reader.api.ApiImp;
import com.resou.reader.api.entry.LoginData;
import com.resou.reader.api.entry.LoginResult;
import com.resou.reader.api.entry.Probability;
import com.resou.reader.api.entry.Result;
import com.resou.reader.api.entry.ResultList;
import com.resou.reader.api.entry.UserInfoBean;
import com.resou.reader.api.entry.VersionBean;
import com.resou.reader.api.service.UserService;
import com.resou.reader.base.ResouBasePresenter;
import com.resou.reader.data.ResouxsRepository;
import com.resou.reader.mine.IView.UserInstance;
import com.resou.reader.utils.AppExecutors;
import com.resou.reader.utils.DeviceUtils;
import com.resou.reader.utils.PreferenceUtil;
import com.resou.reader.utils.SystemUtil;
import com.resou.reader.utils.downupdata.DownloadListener;
import com.resou.reader.utils.downupdata.DownloadUtil;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.resou.reader.utils.log.LogUtil;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class MainPresenter extends ResouBasePresenter<IMainContract.IMainView> implements IMainContract.IMainPresenter {
    private static final String TAG = "MainPresenter";
    UserService userService;
    ProgressBar mProgressBar;
    private ResouxsRepository mRepository;


    public MainPresenter(IMainContract.IMainView view) {
        super(view);
        userService = ApiImp.getInstance().getService(UserService.class);
        mRepository = ResouxsRepository.getInstance();
    }


    /**
     * 版本更新
     */
    public void updataVersion() {
        userService.checkVersionUpdata().subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Observer<Result<VersionBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(Result<VersionBean> result) {
                        if (result.getCode() == 0) {
                            if (result.getData().getVersion_code() > SystemUtil.getVersionCode(mView.getContext())) {
                                mView.showUpdate(result.getData().getApk_url());
                            } else {
                                mView.setToastShow();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(new Throwable("网络异常"));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    public void showUpdataDialog(AlertDialog dialog, AlertDialog.Builder builder, String downUrl) {
        if (null == builder) {
            builder = new AlertDialog.Builder(mView.getContext(), R.style.DialogStyle);
            View view = LayoutInflater.from(mView.getContext()).inflate(R.layout.dialog_updataprogress, null);
            builder.setView(view);
            dialog = builder.create();

            RelativeLayout rlUpdataView = view.findViewById(R.id.rlUpdataView);
            RelativeLayout rlShowUpdata = view.findViewById(R.id.rlShowUpdata);
            ImageView ivClose = view.findViewById(R.id.ivClose);
            TextView tvClose = view.findViewById(R.id.tvClose);
            TextView tvProgress = view.findViewById(R.id.tvProgress);
            ImageButton ibtnUpdata = view.findViewById(R.id.ibtnUpdata);
            mProgressBar = view.findViewById(R.id.mProgressBar);
            ibtnUpdata.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    rlUpdataView.setVisibility(View.VISIBLE);
                    rlShowUpdata.setVisibility(View.GONE);
                    downApk(downUrl, tvProgress);
                }
            });
            AlertDialog finalDialog = dialog;
            ivClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    finalDialog.dismiss();
                }
            });
            tvClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finalDialog.dismiss();
                }
            });
        }
        dialog.show();
    }

    /**
     * 版本更新
     *
     * @param url
     */
    public void downApk(String url, TextView tvProgress) {
        String path = Environment.getExternalStorageDirectory().getPath().toString();
        DownloadUtil.download(url, path, new DownloadListener() {
            @Override
            public void onStart() {
                LogUtil.d(TAG, "开始下载");
            }

            @Override
            public void onProgress(int progress) {
                mView.getContext().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mProgressBar.setProgress(progress);
                        tvProgress.setText(progress + "%");
                    }
                });
            }

            @Override
            public void onFinish(String path) {
                LogUtil.d(TAG, path);
                mView.InstallApk(path);
            }

            @Override
            public void onFail(String errorInfo) {
//                ToastUtil.makeShortToast(errorInfo);
                LogUtil.d(TAG, errorInfo);
            }
        });
    }


    private void UPshSetting(int userId) {
        final PushAgent mPushAgent = PushAgent.getInstance(ReSouApplication.getRSApplication());
        mPushAgent.setAlias(String.valueOf(userId), "type_id", (isSuccess, message) -> {

        });
    }

    @Override
    public void autoLogin() {
        String token = UserInstance.getToken();
        if (!TextUtils.isEmpty(token)) {
            addCompositeDisposable(
                    ApiImp.getInstance().getService(UserService.class)
                            .getUserInfo(token)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(userInfoBeanResult -> {
                                if (userInfoBeanResult.getCode() == 0 && userInfoBeanResult.getData() != null) {
                                    UserInfoBean.UBean uBean = userInfoBeanResult.getData().getU();
                                    if (uBean != null) {
                                        LoginData data = UserInstance.saveUserInfo(uBean);
                                        UserInstance.setToken(token);
                                        //回调登录成功的方法
                                        mView.autoLoginSuccess(data);
                                        //友盟推送用户登录的id
                                        UPshSetting(data.getId());
                                        MessageEvent event = new MessageEvent();
                                        event.isLogin = true;
                                        EventBus.getDefault().post(event);
                                        //用户注册成功后调用
                                        OpenInstall.reportRegister();
                                    }
                                } else {
                                    mView.autoLoginFailed(userInfoBeanResult.getCode());
                                }
                            }, Throwable::printStackTrace)
            );
        }

    }

    @Override
    public void touristLogin(String versionName) {
        userService.touristLogin(DeviceUtils.getIMEI(ReSouApplication.getRSApplication()),
                "游客" + versionName, 100, "android").subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers())
                .subscribe(new Observer<LoginResult<LoginData>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addCompositeDisposable(d);
                    }

                    @Override
                    public void onNext(LoginResult<LoginData> loginDataLoginResult) {
                        if (loginDataLoginResult.getCode() == 0) {
                            /**
                             * 统计新增用户
                             */
                            MobclickAgent.onProfileSignIn("YK", loginDataLoginResult.getData().getId() + "");
                            MobclickAgent.onEvent(ReSouApplication.getRSApplication(), "user_login", "YK");
                            //登录成功后保存登录信息
                            UserInstance.setLoginData(loginDataLoginResult.getData());
                            UserInstance.setToken(loginDataLoginResult.getToken());
                            mView.touristSuccess();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        mView.showError(new Throwable("网络异常"));
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /***
     * 查询广告显示概率
     */
    @Override
    public void quearAdProbability() {
        userService.quearProbability().subscribeOn(getIOSchedulers())
                .observeOn(getMainSchedulers()).subscribe(new Consumer<ResultList<Probability>>() {
            @Override
            public void accept(ResultList<Probability> probabilityResultList) throws Exception {
                List<Probability> list = probabilityResultList.getData();
                if (list != null && list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        if (list.get(i).getType().equals("0") && list.get(i).getChannel().equals("qq")) {
                            PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).saveAdProbability((int) (Float.valueOf(list.get(i).getScale()) * 100));
                        }
                        if (list.get(i).getType().equals("1") && list.get(i).getChannel().equals("qq")) {
                            PreferenceUtil.getInstance(ReSouApplication.getRSApplication()).saveAdProbabilityContent((int) (Float.valueOf(list.get(i).getScale()) * 100));
                        }
                    }
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.i(TAG, "accept: " + throwable);
            }
        });
    }

    /**
     * 从服务器读三天充值状态
     *
     * @param context
     */
    public void saveRechargeActivityState(Context context) {
        AppExecutors.getAppExecutors().networkIO().execute(() -> {
            Boolean isJoin = mRepository.checkRechargeActivity(UserInstance.getToken());
            Log.i("充值", "saveRechargeActivityState: " + isJoin);

            PreferenceUtil.getInstance(context).setShowRechargeDialogToday(!isJoin);
        });
    }
}
